// run: $exec < input
// opt: 0
// flag: -g
#include <iostream>
#include <algorithm>
#include <vector>

int const maxn = 10007;
int const inf = 1 << 30;
bool vis[maxn];
long long a[maxn];
long long b[maxn];
long long cycle[maxn];
int tot, n;

std::vector<int> v;

void get_cycle(int x)
{
	tot = 0; cycle[tot++] = x;
	vis[x] = true;
	for (int i = b[x]; i != x; i = b[i]) {
		vis[i] = true;
		cycle[tot++] = i;
	}
}

int main()
{
	std::ios::sync_with_stdio(false);
	std::cin >> n;
	long long all_min = inf;
	for (int i = 1; i <= n; i++) {
		std::cin >> a[i];
		v.push_back(a[i]);
		all_min = std::min(all_min, a[i]);
	}
	std::sort(v.begin(), v.end());
	for (int i = 1; i <= n; i++)
		b[i] = std::lower_bound(v.begin(), v.end(), a[i]) - v.begin() + 1;

	long long ans = 0;
	for (int i = 1; i <= n; i++) {
		if (vis[i]) continue;
		 get_cycle(i);
		 if (tot <= 1) continue;
		 long long min = inf;
		 long long tmp = 0, tmp2 = 0;
		 for (int j = 0; j < tot; j++) {
			 min = std::min(min, a[cycle[j]]);
			 tmp += a[cycle[j]];
		 }
		 tmp2 = (all_min + min) * 2 + tmp + (tot - 2) * all_min - min + all_min;
		 tmp += (tot - 2) * min;
		 ans += std::min(tmp, tmp2);
	}
	std::cout << ans << '\n';
}

